package cn.com.visionsky.bocsz.bda.webservice.filter;

import cn.com.visionsky.bocsz.bda.webservice.cache.WhiteIpTableCache;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by 46043 on 2016/10/28.
 */
public class WhiteIpTableFilter implements Filter {

    private static final Logger logger = LoggerFactory
            .getLogger(WhiteIpTableFilter.class);

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
        final String enterIp = getIpAddr((HttpServletRequest) request);
        final String enable = WhiteIpTableCache.getWhiteIpTableMap().get(enterIp);
        if(StringUtils.equalsIgnoreCase(enable, "Y")) {
            chain.doFilter(request, response);
        } else {
            logger.info("enter ip:" + enterIp + " not in white ip table or disabled to enter");
        }
    }

    public void destroy() {

    }

    private String getIpAddr(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");

        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        System.out.println("本次登录的用户IP地址："+ ip);
        return ip;
    }


}
